<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试页面</title>
    <link rel="stylesheet" href="css/reset.css">
    <script src="./js/cdn.staticfile.org_jquery_2.0.0_jquery.min.js"></script>
    <script src="./js/unpkg.com_vue@3.3.4_dist_vue.global.js"></script>
    <script src="./js/cdn.jsdelivr.net_npm_axios@1.1.2_dist_axios.min.js"></script>
</head>
<body>
    
<div id="app">
    <div class="grid-container fontSizeSmall">

        <div class="user-list">
            <p style="color: green;">用户列表</p>
            <ul class="ul" style="overflow: auto;">
                <li class="showUser" :class="{'active':item==this.userName?true:false}" v-for="(item,index) in userList" :key="index">【{{ item }}】</li>
            </ul>
            <div class="tip" id="tip" >
                <p style="color: green;margin: 2px;">提示消息：</p>
                <div style="overflow: auto;width: 100%;height: 75%;" id="tipContent">
                    <p style="margin: 2px 0 0 10px ;overflow: hidden;" v-for="(item,index) in time_record" :key="index">
                        <span style="color: #d63504;">【{{item[0]}}】</span>
                        <span style="color: #004bd5;margin: 0 5px;">{{ new Date(item[1]).toLocaleTimeString() }}</span>
                        <span v-if="item[2]=='login'" style="color: #ff0651;">进入了聊天室</span>
                        <span v-else-if="item[2]=='logout'" style="color: #099dff;">离开了聊天室</span>
                        <span v-else style="color: #099dff;">{{item[2]}}</span>
                    </p>
                </div>
                <!-- <p style="margin: 2px 0 0 10px ;font-size: 14px;" v-for="(item,index) in leaveUserList" :key="index">
                    <span style="color: #15d007;">【{{item}}】</span><span>离开了聊天室</span>
                </p> -->
            </div>
        </div>

        <!-- 消息列表 -->
        <div class="content" id="content">
            <div style="margin: 5px;">
                <p >
                    <span style="color: rgb(27, 167, 2);font-size: 18px;font-weight: bolder;">管理员：</span>
                    <span style="color: rgb(168, 0, 76);">欢迎来到本聊天室</span>
                </p>
                <div >
                    <div style="margin: 10px 0px 0px 10px;width: 90%;" v-for="(item,index) in msgList" :key="index">
                        <span v-if="item[0]==userName" style="font-size: 15px;font-weight: bolder;color: rgb(255, 47, 47);margin-right: 10px;">【{{ item[0] }}】:</span>
                        <span v-else style="font-size: 15px;font-weight: bolder;color: rgb(56, 97, 187);margin-right: 10px;">【{{ item[0] }}】:</span>
                        <span style="font-size: 15px;color: rgb(35, 46, 88);">{{ new Date(item[1]).toLocaleTimeString() }}</span>
                        <p style="margin: 2px 0 0 40px;">
                            {{ item[2] }}
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 用户信息 -->
        <div class="userInfo" style="border: 1px solid black;">
            <div class="userInfoDetails">
                <span>用户名：</span><span>{{ userName }}</span>
                <span>性别：</span><span>未知</span>
                <span>年龄：</span><span>未知</span>
                <span v-show="showInput" style="grid-area:4/1/ span 1 / span 2"><input @keyup.enter="editUserName" v-model="newUserName" type="text" placeholder="请输入新的用户名" style="width: 80%;"></span>
                
                <span style="grid-area:5/1/ span 1 / span 2">
                    <button @click="editUserName">{{ editText }}</button>
                    <button style="margin-left: 10px;display: inline;" v-show="editText=='确定'" @click="cancel">取消</button>
                </span>
                
                <span style="position: absolute;bottom: 0px;"><button @click="test">测试功能</button></span>
                
            </div>
            
        </div>

        <div class="operate">
            <div style="width: 95%;height: 50%;margin-top: 5px;">
                <textarea v-model="inputMsg" @keyup="enterEvent" @keydown.alt="keyWarp"  class="inp" type="text" style="width: 100%;height: 100%;resize: none"></textarea>
                <button style="width: 100px;" class="btn" @click="sendMsg">发送</button>
            </div>
        </div>
        
    </div>
</div>



<script type="module">
    // let remoteHost="192.168.253.132"
    import GVar from './js/GVar.js'
    let remoteHost=GVar.RemoteHost
    const { createApp,onBeforeMount,onMounted,nextTick } = Vue
    axios.defaults.baseURL=`http://${remoteHost}:2233/api/`
    const ws = new WebSocket(`ws://${remoteHost}:2233/ws/test/`)
    ws.binaryType="arraybuffer"
    const app = createApp({
        data() {
            return {
                message: 'Hello Vue!',
                data:'',
                inputMsg:'',
                msgId:0,
                msgList:[],
                timer:null,
                userList:[],
                time_record:[],
                shiw_time_record_id:0,
                newUserList:[],
                leaveUserList:[],
                userName:'',
                showInput:false,
                newUserName:'',
                editText:"修改用户名"
            }
        },
        beforeMount(){
            this.userName=localStorage.getItem('userName')
            if(!this.userName){
                this.userName=(new Date).getTime().toString().substring(4)
            }
        },
        watch:{
            time_record: {
                handler(val, oldVal) {
                    nextTick(()=>{
                        // 把滚动条拉到底部
                        document.getElementById("tipContent").scrollTop = document.getElementById("tipContent").scrollHeight
                    })
                },
                deep:true  // 深度监听
            },
            msgList:{
                handler(val, oldVal) {
                    nextTick(()=>{
                        // 把滚动条拉到底部
                        document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight
                    })
                    
                },
                deep:true  // 深度监听
            }
        }
        ,
        mounted(){
            // axios.get('/sendmsg/').then(res=>this.data=res.data.data)

            // this.timer = setInterval(this.receiveMsg,2000)

            // clearInterval(this.timer)
            // setTimeout(()=>clearInterval(this.timer),10000)
            
            // this.registerUser()
            
            
            // this.receiveMsg()
            ws.onopen = ()=>{
                console.log('连接已建立');
                this.registerUser()
            }
            ws.onerror = ()=>{
                console.log('连接发生错误');
            }
            ws.onmessage = (event)=>{
                console.log('收到了新消息');
                
                let result = JSON.parse(event.data)
                if(result.callback){
                    this[result.callback](result)
                }
            }
            ws.onclose = ()=>{
                console.log('连接已关闭');
            }
            
        },
        methods:{
            registerUser(){
                let sendData={
                    getType:'register',
                    userName:this.userName,
                    msgId:this.msgList.length
                }
                ws.send(JSON.stringify(sendData))  // 用户连接注册
                
                // let sendData2={
                //     getType:'getAllUser',
                //     userName:this.userName,
                    
                // }
                // ws.send(JSON.stringify(sendData2))  // 获取所有在线用户
            },
            registerUserRet(result){
                if(result.code==200){
                    if(result.historyMsgList && result.historyMsgList.length>0){  // 获取历史消息，最多20条
                        this.msgList = result.historyMsgList
                    }
                    if(this.userName != result.userName){
                        alert('相同的用户名已存在，系统自动为你更改为 '+result.userName)
                        this.userName = result.userName
                    }
                    localStorage.setItem('userName',this.userName)
                    
                }
                
            },
            
            getAllUserRet(result){  // 处理getAllUser请求返回的结果
                // let temp=result.userList
                // // 判断新进来的用户有哪些，如果本地的用户没有返回的用户，则表示这个用户是新进来的
                // let tempNewUserList = temp.filter(item=>{
                //     if(this.userList.indexOf(item)<0){
                //         return true
                //     }
                // })
                // this.newUserList = this.newUserList.concat(tempNewUserList)

                // // 判断离开的用户有哪些，如果返回的用户列表中没有某个本地的用户，则是用户离开了
                // let tempLeaveUserList = this.userList.filter(item=>{
                //     if(temp.indexOf(item)){
                //         return true
                //     }
                // })
                // this.leaveUserList = this.leaveUserList.concat(tempLeaveUserList)

                this.userList=result.userList  // 保存新的在线用户列表

                if(result.time_record && result.time_record.length>0){
                    // 时间记录
                    let index = 0
                    let temp = this.time_record
                    let t1 = setInterval(function(){
                        if(result.time_record[index]){
                            console.log(result.time_record);
                            temp.push(result.time_record[index])
                        }else{
                            clearInterval(t1)
                            return
                        }
                        index += 1
                    },1000)
                }
                
                
                // this.time_record = this.time_record.concat(result.time_record)

            },
            test(){
                console.log( document.getElementById("tip").scrollHeight);
                document.getElementById("tip").scrollTop = document.getElementById("tip").scrollHeight;
            },
            getAllUser(){    // 获取所有在线用户，并获取历史消息20条
                let sendData={
                    getType:'getAllUser',
                    userName:this.userName,
                    msgId:this.msgList.length
                }
                ws.send(JSON.stringify(sendData))

                return
                
            },
            enterEvent(key){
                // 用户按下回车键，且没有按下alt键，则发送消息。按下alt+Enter键，只换行，不发送消息
                if(key.key=='Enter' && !key.altKey){

                    this.sendMsg()
                }
            },
            sendMsg(){
                let sendData={
                    getType:'sendMsg',
                    userName:this.userName,
                    msg:this.inputMsg
                }
                ws.send(JSON.stringify(sendData))
                this.inputMsg=''

            },
            keyWarp(key){  // 换行
                if(key.key=='Enter'){
                    this.inputMsg+='\n'
                }else{
                    // console.log(key.key);
                }
            },
            receiveMsg(result){
                this.msgList.push(result.data)

                // axios.get('/receiveMsgLong/',{
                //     params:{userName:this.userName}
                // }).then(res=>{
                //     if(res.data.code==200){
                //         let newMsgList = res.data.data.newMsgList.map(item=>JSON.parse(item))
                //         this.msgList = this.msgList.concat(newMsgList)
                //         this.userList = res.data.data.userList
                //         this.receiveMsg()
                //     }else{
                //         this.userList = res.data.data.userList
                //         this.receiveMsg()
                //     }

                    
                // })
            },
            editUserName(){
                if(this.editText=="修改用户名"){
                    this.showInput=true
                    this.editText="确定"
                    return
                }else{
                    this.showInput=false
                    this.editText="修改用户名"
                }
                // console.log(this.newUserName);
                this.newUserName = this.newUserName.trim()
                let sendMsg = {
                    getType:'editUser',
                    newUserName:this.newUserName,
                    oldUserName:this.userName
                }

                ws.send(JSON.stringify(sendMsg))
                
                return
            },
            editUserRet(result){
                // this.getAllUserRet(result)
                if(result.code==200){
                    console.log('sdfasdfasf');
                    this.userName = result.newUserName
                    localStorage.setItem('userName',this.userName)
                }else{
                    alert(result.msg)
                }

            },
            cancel(){
                
                this.showInput=false
                this.editText="修改用户名"
                this.newUserName=''
            },
            showTimeRecord(){
                
            }
        }

    }).mount('#app')
</script>
<style>
    body{
        /* background-color: #9dd6fd; */
        background-color: #246b9b;
    }
    #app{
        
    }
    .fontSizeSmall{
        font-size: 14px;
    }
    .grid-container{
        background-color:#9dd6fd;
        box-sizing: border-box;
        margin: 10px auto;
        padding: 5px;
        display: grid;
        width: 1120px;
        height: 630px;
        border: 1px solid black;
        grid-template:2fr 1fr / 1fr 2fr;
        grid-gap:5px;
    }
    .grid-container >*{
        background-color: #fefefe;
    }
    .user-list{
        overflow: auto;
        border: 1px solid black;
        /* grid-area:1 / 1 / span 2 / span 1; */
        /* overflow: auto; */
        cursor: default;
        position: relative;
    }
    .content{
        overflow: auto;
        border: 1px solid black;
    }
    .userInfo{
        position: relative;
    }
    .operate{
        border: 1px solid black;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    ul {
        list-style: none;
    }
    .showUser{
        color:rgb(2, 40, 110);
        width: auto;
        /* font-size: 16px; */
        margin: 5px 8px;
        /* border-bottom: 1px solid black; */
    }
    .showUser.active{
        color: red;
        font-weight: bolder;
    }
    .showUser:hover{
        background-color: rgb(255, 194, 10);
    }
    .tip{
        position: absolute;
        bottom: 0px;
        border-top: 1px solid black; 
        height: 20%;
        width: 100%;
        /* overflow: auto; */
    }


    .userInfoDetails{
        margin: 5px;
        display: grid;
        grid-template:1fr 1fr / 1fr 3fr;
        grid-gap:10px 0px
    }

</style>
</body>
</html>